<template>

  <el-dialog :title="id ? '返佣结算修改' : '返佣结算添加'" :visible.sync="dialogVisible" :close-on-click-modal="false" width="50%">

    <el-form ref="main-form" :model="form" :rules="rules" label-width="140px" >
      <el-form-item label="银行通道" size="mini" prop="channelId">
        <el-select v-model="form.channelId" size="small" clearable :disabled="id != null">
          <el-option
            v-for="item in channelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="返佣人" size="mini" prop="channelIntroducerId">
        <el-select v-model="form.channelIntroducerId" size="small" clearable :disabled="id != null">
          <el-option
            v-for="item in channelIntroducerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="渠道名称" size="mini" prop="formulaName">
        <el-input placeholder="" v-model="form.formulaName" @keyup.enter.native="submit" clearable style="width: 500px;"></el-input>
      </el-form-item>

      <el-form-item label="计算公式" size="mini" prop="formula">
        <el-select v-model="form.formula" size="small" clearable style="width: 500px;">
          <el-option
            v-for="item in bankChannelCommissionFormulaOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="佣金比例(%)" size="mini" prop="percentage">
        <el-input placeholder="佣金比例(%)" type="number" v-model="form.percentage" @keyup.enter.native="submit" clearable style="width: 500px;"></el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close" size="small">取 消</el-button>
      <el-button type="primary" @click="submit" size="small" :loading="loading">提 交</el-button>
    </div>

  </el-dialog>
</template>

<script>
import ChannelApiMain from '@/api/bank.channel';
import ChannelIntroducerApiMain from '@/api/bank.channelIntroducer';
import ApiMain from '@/api/formula';
export default {
  mixins: [
  ],
  props: [
  ],
  data () {
    return {

      dialogVisible: false,
      popDeleteVisible: false,
      loading: false,

      form: {
        channelId: '',
        channelIntroducerId: '',
        type: 4,
        handType: 0,
        percentage: 0,
        formulaName: '',
        formula: '',
        formulaToCount: '',
        params: '',
        status: 1,
      },

      rules: {
        channelId: [
          { required: true, message: '请选择银行通道', trigger: 'blur' },
        ],
        channelIntroducerId: [
          { required: true, message: '请选择返佣人', trigger: 'blur' },
        ],
        formula: [
          { required: true, message: '请选择计算公式', trigger: 'blur' },
        ],
        percentage: [
          { required: true, message: '请填写比例', trigger: 'blur' },
          { trigger: 'blur', validator: function (rule, value, callback) {
            if (value < 0 || value > 100) {
              callback(new Error('比例0-100'));  
            } else {
              callback();
            }
          }},
        ],
        formulaName: [
          { required: true, message: '请填写渠道名称', trigger: 'blur' },
          { min: 2, max: 15, message: '2-15个字符', trigger: 'blur' },
        ],
      },

      id  : null,
      data: null,

      channelOptions: [],
      channelIntroducerOptions: [],
      bankChannelCommissionFormulaOptions: [],

    }
  },
  mounted () {
  },

  methods: {

    show (id = null) {

      this.id = id;

      if (this.id) {
        this.fetchData();
      }
      else {
        this.reset();
      }

      // 加载通道，返佣人
      this.fetchChannelFormulaOption();
      this.fetchChannelOption();
      this.fetchChannelIntroducerOption();

      this.dialogVisible = true;
    },

    close () {
      this.dialogVisible = false;
      this.$emit('dialog-close');
    },

    reset () {
      this.form = {
        channelId: '',
        channelIntroducerId: '',
        type: 4,
        handType: 0,
        percentage: 0,
        formulaName: '',
        formula: '',
        formulaToCount: '',
        params: '',
        status: 1,
      };
    },

    fetchChannelFormulaOption () {
      ApiMain.option({ type: 4 }).then(re => {
        this.bankChannelCommissionFormulaOptions = re;
      })
    },

    fetchChannelOption () {
      ChannelApiMain.option().then(re => {
       this.channelOptions = re;
      })
    },

    fetchChannelIntroducerOption () {
      ChannelIntroducerApiMain.option().then(re => {
       this.channelIntroducerOptions = re;
      })
    },

    fetchData () {

      ApiMain.info({id: this.id})
      .then(re => {
        this.data = re; 
      })
      .catch(() => {
        this.data = null;
      })
      .finally(() => {
        this.renderData();
      });
    },

    renderData () {
      this.form.formulaName = this.data.formulaName;
      this.form.channelId = this.data.channelId;
      this.form.channelIntroducerId = this.data.channelIntroducerId;
      this.form.formula = this.data.formula;
      this.form.percentage = this.data.params ? JSON.parse(this.data.params).percentage / 100 : 0;
      this.form.status = this.data.status;
    },

    verifyForm () {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async submit () {

      if (! this.verifyForm()) return false;

      this.loading = true;

      try {
        if (this.id) {
          await this.submitSet();
        }
        else {
          await this.submitAdd();
        }
      } finally {
        this.loading = false;
      }
    },

    formatSubmitForm (form) {
      // 将比例给进公式里
      form.formulaToCount = form.formula;
      form.params = JSON.stringify({ percentage: Number(form.percentage * 100).toFixed(0) });
      return form
    },

    async submitDel() {

      this.popDeleteVisible = false;
      this.loading = true;

      await ApiMain.del({id: this.id});

      this.loading = false;
      this.close();
      this.$message({message: '删除成功', type: 'success'});
    },

    async submitSet () {

      this.form.id = this.id;
      let form = Object.copy(this.form)
      form = this.formatSubmitForm(form)
      await ApiMain.set(form);
      this.$message({message: '修改成功', type: 'success'});
      this.close();

    },

    async submitAdd () {
      let form = Object.copy(this.form)
      form = this.formatSubmitForm(form)
      await ApiMain.add(form);
      this.$message({message: '添加成功', type: 'success'});
      this.close();
    },
  }
}
</script>

<style>

</style>
